package com.example.myfirstdemo.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.myfirstdemo.R;
import com.example.myfirstdemo.dialog.PhotoPopupWindow;
import com.example.myfirstdemo.utils.Constants;
import com.example.myfirstdemo.utils.InfoPrefs;
import com.example.myfirstdemo.utils.PictureUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;


public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "UserInfoActivity";
    private static final int REQUEST_IMAGE_GET = 200;
    private static final int REQUEST_IMAGE_CAPTURE = 300;
    private static final int REQUEST_CHANGE_USER_NICK_NAME = 10;

    PhotoPopupWindow mPhotoPopupWindow;
    TextView textView_user_nick_name;
    TextView textView_user_gender;
    CircleImageView circleImageView_user_head;
    Uri uri;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);

        textView_user_nick_name = findViewById(R.id.user_nick_name_TV);
        textView_user_gender = findViewById(R.id.user_gender_TV);
        circleImageView_user_head = findViewById(R.id.user_head_iv);

        //InfoPrefs自己封装的一个 SharedPreferences 工具类
        //init()指定文件名，getData(String key)获取key对应的字符串，
        // getIntData(int key)获取key对应的int

        InfoPrefs.init("user_info");

        RelativeLayout relativeLayout_user_nick_name = findViewById(R.id.user_nick_name);
        relativeLayout_user_nick_name.setOnClickListener(this);

        RelativeLayout relativeLayout_user_gender = findViewById(R.id.user_gender);
        relativeLayout_user_gender.setOnClickListener(this);

        RelativeLayout relativeLayout_user_head = findViewById(R.id.user_head);
        relativeLayout_user_head.setOnClickListener(this);
        //初始化toolbar
        Toolbar toolbar = findViewById(R.id.toolbar_userinfo);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        if(actionBar != null){
            //指定toolbar左上角的返回按钮，这个按钮的id是home（无法更改）
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.user_head:
                //创建存放头像的文件夹
                PictureUtil.mkdirMyFirstDemoRootDirectory();
                mPhotoPopupWindow = new PhotoPopupWindow(UserInfoActivity.this,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 文件权限申请
                                if(ContextCompat.checkSelfPermission(
                                        UserInfoActivity.this,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        != PackageManager.PERMISSION_GRANTED){
                                    //权限还没有授予，进行申请
                                    ActivityCompat.requestPermissions(UserInfoActivity.this,
                                            new String[]{Manifest.permission.
                                                    WRITE_EXTERNAL_STORAGE},REQUEST_IMAGE_GET);
                                    //申请的 requestCode 为200
                                }else {
                                    //权限已经申请，直接进行图片选择
                                    mPhotoPopupWindow.dismiss();
                                    openAlbum();
                                }
                            }
                        }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //拍照及文件权限申请
                        if(ContextCompat.checkSelfPermission(UserInfoActivity.this,
                                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                                || ContextCompat.checkSelfPermission(UserInfoActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
                        PackageManager.PERMISSION_GRANTED){
                            //权限还没有授予，进行申请
                            ActivityCompat.requestPermissions(UserInfoActivity.this,
                                    new String[]{Manifest.permission.CAMERA,Manifest.
                                            permission.WRITE_EXTERNAL_STORAGE},REQUEST_IMAGE_CAPTURE);
                            //申请的requestCode为300
                        }else {
                            //权限已申请直接拍照
                            mPhotoPopupWindow.dismiss();
                            imageCapture();
                        }
                    }
                });
                View rootView = LayoutInflater.from(UserInfoActivity.this).inflate(R.
                        layout.activity_userinfo,null);
                mPhotoPopupWindow.showAtLocation(rootView, Gravity.BOTTOM |
                        Gravity.CENTER_HORIZONTAL,0,0);
                break;
            case R.id.user_nick_name:
                break;
            case R.id.user_gender:
                break;
            default:
        }
    }

    private void openAlbum(){
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        //判断系统中是否有处理改 Intent 的Activity
        startActivityForResult(intent,REQUEST_IMAGE_GET);
    }

    /**
     * 4.4版本以上对返回的图片Uri的处理：
     * 返回的Uri是经过封装的，要进行处理才能得到真实路径
     * @param data 调用系统相册之后返回的Uri
     */
    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是File类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        //根据图片路径显示图片
        displayImage(imagePath);
    }

    private void handleImageBefore(Intent data){
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    //将imagePath指定的图片显示到ImageView上
    private void displayImage(String imagePath) {
            if(imagePath != null){
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                circleImageView_user_head.setImageBitmap(bitmap);
            }else {
                Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
                circleImageView_user_head.setImageResource(R.mipmap.bg);
            }
        }

    /**
     * 将Uri转化为路径
     * @param uri 要转化的Uri
     * @param selection 4.4之后需要解析Uri，因此需要该参数
     * @return 转化之后的路径
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        //回调成功
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG,"*****************************"+resultCode);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                //相机
                case REQUEST_IMAGE_CAPTURE:
                    Bitmap bitmap = null;
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                        circleImageView_user_head.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                //相册
                case REQUEST_IMAGE_GET:
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                        handleImageOnKitkat(data);
                    }else {
                        handleImageBefore(data);
                    }
                    break;
                //获取changeinfo销毁后回传数据
                case REQUEST_CHANGE_USER_NICK_NAME:
                    String returnData = data.getStringExtra("data_return");
                    InfoPrefs.setData(Constants.UserInfo.NAME,returnData);
                    textView_user_nick_name.setText(InfoPrefs.getData(Constants.UserInfo.NAME));
                    break;
                default:
            }
        }else {
            Log.e(TAG,"result="+resultCode+",request="+requestCode);
        }
    }

    private void imageCapture(){
        File file = new File(getExternalCacheDir(),"user_head_uri.jpg");

        try {
            if(file.exists()){
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断android系统的版本
        if(Build.VERSION.SDK_INT >= 24){
            uri = FileProvider.getUriForFile(UserInfoActivity.this,
                    "com.example.myfirstdemo.fileProvier",file);
        }else {
            uri = Uri.fromFile(file);
        }

        //启动相机
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //指定图片的输出地址
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(takePhotoIntent,REQUEST_IMAGE_CAPTURE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_IMAGE_GET:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPhotoPopupWindow.dismiss();
                    openAlbum();
                    // 判断系统中是否有处理该 Intent 的 Activity
                } else {
                    Toast.makeText(UserInfoActivity.this, "未找到图片查看器", Toast.LENGTH_SHORT).show();
                    mPhotoPopupWindow.dismiss();
                }
                break;
            case REQUEST_IMAGE_CAPTURE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPhotoPopupWindow.dismiss();
                    imageCapture();
                } else {
                    mPhotoPopupWindow.dismiss();
                }
                break;
        }
    }


    //头像相关到此结束

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


}
